class Gallery31 {
	var $meta_fields = array("p31-description", 
									 "p31-location", 
									 "p31-year", 
									 "p31-camera-used");
	
	function Gallery31()
	{
	
      $labels = array(
        'name' => _x('Galleries', 'post type general name'),
        'singular_name' => _x('Gallery', 'post type singular name'),
        'add_new' => _x('Add New', 'Gallery'),
        'add_new_item' => __('Add New Gallery'),
        'edit_item' => __('Edit Gallery'),
        'new_item' => __('New Gallery'),
        'view_item' => __('View Gallery'),
        'search_items' => __('Search Galleries'),
        'not_found' =>  __('No Galleries found'),
        'not_found_in_trash' => __('No Galleries found in Trash'),
        'parent_item_colon' => ''
      );
	
		// Register custom post types
		register_post_type('gallery', array(	
         'labels' => $labels,              // See above
			'singular_label' => __('Gallery'),
			'public' => true,
			'show_ui' => true, // UI in admin panel
			'_builtin' => false, // It's a custom post type, not built in
			'capability_type' => 'post',
			'hierarchical' => false,
			'rewrite' => array("slug" => "galleries"), // Permalinks
         'has_archive' => true, 			
         'menu_position' => 2,
			'query_var' => "gallery", // This goes to the WP_Query schema
			'supports' => array( 'title', 'editor', 'thumbnail' ) // Let's use custom fields for debugging purposes only
		));
		
		add_filter("manage_edit-gallery_columns", array(&$this, "edit_columns"));
		add_action("manage_posts_custom_column", array(&$this, "custom_columns"));
		
		// Register custom taxonomy
		register_taxonomy("photo_category", 
								array("gallery"), 
								array("hierarchical" => true, 
										"label" => "Photo Categories", 
										"singular_label" => "Photo Category", 
										"rewrite" => true)
								);

		// Admin interface init
		add_action("admin_init", array(&$this, "admin_init"));
		//add_action("template_redirect", array(&$this, 'template_redirect'));
		
		// Insert post hook
		add_action("wp_insert_post", array(&$this, "wp_insert_post"), 10, 2);
	}
	
	function edit_columns($columns)
	{
		$columns = array(
			"cb" => "<input type=\"checkbox\" />",
			"title" => "Photo Title",
			"p31_location" => "Location",
			"p31_year" => "Year",
			"p31_photo_category" => "Photo Category",
		);
		
		return $columns;
	}
	
	function custom_columns($column)
	{
		global $post;
		switch ($column)
		{
			case "p31_description":
				$custom = get_post_custom();
				echo $custom["p31-description"][0];
				break;
			case "p31_location":
				$custom = get_post_custom();
				echo $custom["p31-location"][0];
				break;
			case "p31_year":
				$custom = get_post_custom();
				echo $custom["p31-year"][0];
				break;
			case "p31-camera-used":
				$custom = get_post_custom();
				echo $custom["p31-camera-used"][0];
				break;
			case "p31_photo_category":
				$photo_categories = get_the_terms(0, "photo_category");
				$photo_categories_html = array();
				foreach ($photo_categories as $photo_category)
					array_push($photo_categories_html, 
					'<a href="' . get_term_link($photo_category->slug, "photo_category") . '">' . $photo_category->name . '</a>');
				
				echo implode($photo_categories_html, ", ");
				break;
		}
	}
	
	// Template selection
	function template_redirect()
	{
		global $wp;
		if ($wp->query_vars["post_type"] == "gallery")
		{
			include(CHILDPATH . "/single-gallery.php");
			die();
		}
	}
	
	// When a post is inserted or updated
	function wp_insert_post($post_id, $post = null)
	{
		if ($post->post_type == "gallery")
		{
			// Loop through the POST data
			foreach ($this->meta_fields as $key)
			{
				$value = @$_POST[$key];
				if (empty($value))
				{
					delete_post_meta($post_id, $key);
					continue;
				}

				// If value is a string it should be unique
				if (!is_array($value))
				{
					// Update meta
					if (!update_post_meta($post_id, $key, $value))
					{
						// Or add the meta data
						add_post_meta($post_id, $key, $value);
					}
				}
				else
				{
					// If passed along is an array, we should remove all previous data
					delete_post_meta($post_id, $key);
					
					// Loop through the array adding new values to the post meta as different entries with the same name
					foreach ($value as $entry)
						add_post_meta($post_id, $key, $entry);
				}
			}
		}
	}
	
	function admin_init() 
	{
		// Custom meta boxes for the edit gallery screen
		add_meta_box("p31-meta", "Photo Options", array(&$this, "meta_options"), "gallery", "normal", "high");
	}
	
	// Admin post meta contents
	function meta_options()
	{
		global $post;
		$custom = get_post_custom($post->ID);
		$description = $custom["p31-description"][0];
		$location = $custom["p31-location"][0];
		$year = $custom["p31-year"][0];
		$camera_used = $custom["p31-camera-used"][0];
      ?>
      <p>
      	<label> Description: </label><textarea name="p31-description" rows="1" cols="80"><?php echo $description; ?></textarea>
      </p>
      <p>	
      	<label> Location: </label><input name="p31-location" value="<?php echo $location; ?>" />&nbsp;&nbsp;&nbsp;&nbsp;
      	<label> Year: </label><input name="p31-year" value="<?php echo $year; ?>" />&nbsp;&nbsp;&nbsp;&nbsp;
      	<label> Camera Used: </label><input name="p31-camera-used" value="<?php echo $camera_used; ?>" />
      </p>
      <?php
	}
	
	function gallery_archive_loop() {
      global $post;
      
      $args = array( 'post_type' => 'gallery', 'posts_per_page' => 9 );
      $loop = new WP_Query( $args );
      
      while ( $loop->have_posts() ) : $loop->the_post();
         $dgs_post_thumbnail = get_the_post_thumbnail($loop->ID, array('size' => 'Gallery'));
         $custom = get_post_custom($loop->ID);
         
         $description = $custom["p31-description"][0];
         $location = $custom["p31-location"][0];
         $year = $custom["p31-year"][0];
         $camera_used = $custom["p31-camera-used"][0];    
         $dgs_image_url = get_permalink() . $loop->post_name; 
         
         ?>
         <div class="gallery"> 
            <h2><a href="<?php echo $dgs_image_url; ?>">
               <?php echo get_the_title( $loop->ID ); ?>
            </a></h2>         
            <a href="<?php echo $dgs_image_url;  ?>"> 
                     <?php echo $dgs_post_thumbnail; ?> 
            </a>
            <p>       
               <?php echo $description . '<br />'; ?>
            </p>
         </div>           
         
         <?php
      endwhile;      
	}
	
	function gallery_single_loop() {
      global $post;
      
      $gallery_single_post_id = get_the_ID();
      
      
      $args = array( 'post_type' => 'gallery', 'id' => "$gallery_single_post_id" );
      $loop = new WP_Query( $args );
      
      while ( $loop->have_posts() ) : $loop->the_post();
         $dgs_post_thumbnail = get_the_post_thumbnail($loop->ID, array('size' => 'Gallery'));
         $custom = get_post_custom($loop->ID);
         
         $description = $custom["p31-description"][0];
         $location = $custom["p31-location"][0];
         $year = $custom["p31-year"][0];
         $camera_used = $custom["p31-camera-used"][0];    
         $dgs_image_url = get_permalink() . $loop->post_name; 
         
         if ( get_the_ID() == $gallery_single_post_id ) {
         ?>
         <div class="gallery-image"> 
            <h2><a href="<?php get_permalink(); ?>">
               <?php echo get_the_title( $loop->ID ); ?>
            </a></h2>         
            <a href="<?php get_permalink();  ?>"> 
                     <?php the_content(); ?> 
            </a>
            <p>       
               <?php echo $description . '<br />'; ?>
            
               <table>
                  <tr>
                     <td>Location: </td>
                     <td><?php echo $location; ?></td>
                  </tr>
                  <tr>
                     <td>Year: </td>
                     <td><?php echo $year; ?></td>
                  </tr>
                  <tr>
                     <td>Camera: </td>
                     <td><?php echo $camera_used; ?></td>
                  </tr>                                    
               </table>
            </p>
         </div>           
         
         <?php
         }
      endwhile;      
	}
	
}

// Initiate the plugin - TEST
add_action("init", "Gallery31Init");
function Gallery31Init() { 
	global $p31; 
	$p31 = new Gallery31(); 
}